"""
记录出入信息业务类
    uid - 账号/车牌号
    rType - 1出校、0入校
    rTime - 时间
"""
import time


class RecordService:
    # 写出、入校记录
    def insert(self, uid, rType, uType):
        # 获取当前时间
        t = time.localtime(time.time())
        rTime = f"{t.tm_year}-{t.tm_mon}-{t.tm_mday}"

        if self.isRecordType(uid, rType):
            # 最多出校次数，学生1次 老师和汽车2次
            maxCount = 1 if uType == "1" else 2
            # 获取当前记录命中数
            count = self.recordCount(uid, rType)
            if count >= maxCount:
                # 超过出校次数，禁止通行
                typeName = "学生" if uType == "1" else "老师"
                print(f"【error】禁止通行，今天次数已超限，{typeName}一天只能通行{maxCount}次。")
                return False
            else:
                # 放行 ,写入文件操作
                print(f"<< 允许通行,通行时间:{rTime}")
                file = open("file_record.txt", "a")
                # 当前对象以字符串形式写到文件 以 空格%%空格 分隔
                recordItem = f"{uid} %% {rType} %% {rTime}\n"
                file.write(recordItem)
                file.close()
                return True
        else:
            print(f"【error】 您不可以同时出校/入校两次。")
            return False

    # 判断最近一条命中条数的出入状态，防止非法操作：出去两次或者进入两次
    def isRecordType(self, uid, rType):
        # 获取全部记录
        record_list = self.findAll()
        # 如果是空文件,也即是空集合,直接放行
        if len(record_list) == 0:
            return True
        # 反转列表，倒序遍历
        record_list.reverse()
        for record in record_list:
            # 命中账户通行记录后再次判断当前通行类型是否与用户请求的通行类型一致
            if record[0] == uid:
                # 请求两次相同的通行类型，非法操作
                if record[1] == str(rType):
                    return False
                else:
                    # 放行
                    return True
        return True

    # 返回当天出入校命中条数
    def recordCount(self, uid, rType):
        count = 0
        # 获取今天日期
        t = time.localtime(time.time())
        rTime = f"{t.tm_year}-{t.tm_mon}-{t.tm_mday}"
        # 获取全部记录
        record_list = self.findAll()
        for record in record_list:
            if record[0] == uid and record[1] == str(rType) and record[2] == rTime:
                count += 1
        return count

    # 查找所有记录
    @staticmethod
    def findAll():
        record_list = []
        file = open("file_record.txt")
        recordFileList = file.readlines()
        for i in recordFileList:
            recordItemList = i.replace("\n", "").split(" %% ")
            record_list.append(recordItemList)
        return record_list
